﻿
CREATE PROCEDURE [dbo].[DefekturaCategoriesVsDepartmentsInsert]
(
	@DefekturaCategoryId int,
	@DepartmentId int,
	@SeekDuration int,
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
) 
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @intNextId int
	SET NOCOUNT ON

IF (@DefekturaCategoryId Is Null) OR (@DepartmentId Is Null) OR (@SeekDuration Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF EXISTS (SELECT TOP 1 ID FROM CA.DefekturaCategoriesVsDepartments 
WHERE DefekturaCategoryId = @DefekturaCategoryId 
AND DepartmentId = @DepartmentId
AND ToDelete = 0)
BEGIN
	SELECT @intErrCode = 2, @strMsg = 'Дублируется категория для подразделения!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF NOT EXISTS (SELECT DepartmentId FROM PR.DepartmentOptions WHERE DepartmentId = 0 ) 
BEGIN
	SELECT @intErrCode = 3, @strMsg = 'Изменять данные спрвочников можно только в офисе!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Common', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet


	SET NOCOUNT OFF;

INSERT INTO CA.DefekturaCategoriesVsDepartments
( Id, DefekturaCategoryId, DepartmentId, SeekDuration, [Note], [MD], [MW]) 
VALUES ( @intNextId, @DefekturaCategoryId, @DepartmentId, @SeekDuration, @Note, @MD, @MW);
	
SELECT Id, DefekturaCategoryId AS CategoryId, DepartmentId, SeekDuration, Note, 
MD AS ChangeDateTime, MW AS ChangeWhom, ToDelete
FROM CA.DefekturaCategoriesVsDepartments WHERE (Id = @intNextId)

RETURN 0
